package com.snail.billing.fragment;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.Html;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.TranslateAnimation;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.android.net.HttpApp;
import com.android.net.HttpResult;
import com.android.net.HttpSession;
import com.android.net.OnHttpResultListener;
import com.android.os.Page;
import com.android.util.ResUtil;
import com.snail.billing.Resource;
import com.snail.billing.data.WorkDataManager;
import com.snail.billing.fragment.view.PullToRefreshListView;
import com.snail.billing.json.JsonBase;
import com.snail.billing.json.JsonWorkQuery;
import com.snail.billing.session.WorkDeleteSession;
import com.snail.billing.session.WorkQuerySession;

public class WorkMainFragment extends Page implements View.OnClickListener, OnHttpResultListener, ViewPager.OnPageChangeListener {

	private TextView textTitle;
	private View buttonBack;

	private View layout;
	// private View indicatorLayout;
	private TextView textTab1;
	private TextView textTab2;
	private TextView textTab3;
	private View indicatorTab;
	private ViewPager pager;
	private View button;

	// private Handler handler;

	private HttpApp httpApp;
	private WorkQuerySession workQuerySession1;
	private WorkQuerySession workQuerySession2;
	private WorkQuerySession workQuerySession3;
	private JsonWorkQuery jsonWorkQuery1;
	private JsonWorkQuery jsonWorkQuery2;
	private JsonWorkQuery jsonWorkQuery3;

	private boolean isDialogUseful;
	private PullToRefreshListView listView;

	private int page;
	private int oldMoveX;

	@Override
	public int createLayoutId() {
		return ResUtil.getLayoutId(Resource.layout.snailbilling_work_main_activity);
	}

	@Override
	public void onCreate() {
		super.onCreate();
		textTitle = (TextView) findViewById(ResUtil.getViewId(Resource.id.snailbilling_title_text));
		textTitle.setText("我的提问");
		buttonBack = findViewById(ResUtil.getViewId(Resource.id.snailbilling_title_button_back));
		buttonBack.setOnClickListener(this);
		//
		layout = findViewById(ResUtil.getViewId(Resource.id.snailbilling_work_main_layout));
		layout.setVisibility(View.GONE);
		textTab1 = (TextView) findViewById(ResUtil.getViewId(Resource.id.snailbilling_work_main_indication_tab_text1));
		textTab1.setOnClickListener(this);
		textTab2 = (TextView) findViewById(ResUtil.getViewId(Resource.id.snailbilling_work_main_indication_tab_text2));
		textTab2.setOnClickListener(this);
		textTab3 = (TextView) findViewById(ResUtil.getViewId(Resource.id.snailbilling_work_main_indication_tab_text3));
		textTab3.setOnClickListener(this);
		// indicatorLayout = findViewById(ResUtil.getViewId(Resource.id.snailbilling_work_main_indicator_layout));
		indicatorTab = findViewById(ResUtil.getViewId(Resource.id.snailbilling_work_main_indication_tab));
		pager = (ViewPager) findViewById(ResUtil.getViewId(Resource.id.snailbilling_work_main_pager));
		pager.setOnPageChangeListener(this);
		button = findViewById(ResUtil.getViewId(Resource.id.snailbilling_work_main_button));
		button.setOnClickListener(this);
	}

	@Override
	public void onResume() {
		super.onResume();
		// handler = new Handler(Looper.getMainLooper());
		httpApp = new HttpApp(getContext());
		if (WorkDataManager.getInstance().isEmpty()) {
			isDialogUseful = true;
			requestAllWorkQuery(0);
		} else {
			updateViewTab();
			pager.setAdapter(new MyPageAdapter());
			layout.setVisibility(View.VISIBLE);
			// postIndication(true);
			pager.setCurrentItem(page);
		}
	}

	private void updateViewTab() {
		textTab1.setText(Html.fromHtml("<span>全部(<font color=\"#ff363f\">" + WorkDataManager.getInstance().getCountAll() + "</font>)</span>"));
		textTab2.setText(Html.fromHtml("<span>待解决(<font color=\"#ff363f\">" + WorkDataManager.getInstance().getCountNo() + "</font>)</span>"));
		textTab3.setText(Html.fromHtml("<span>已解决(<font color=\"#ff363f\">" + WorkDataManager.getInstance().getCountYes() + "</font>)</span>"));
	}

	// private void postIndication(final boolean isSetPage) {
	// handler.post(new Runnable() {
	//
	// @Override
	// public void run() {
	// int indicatorTabWidth = indicatorLayout.getWidth() / 3;
	// ViewGroup.LayoutParams layoutParams = indicatorTab.getLayoutParams();
	// if (layoutParams.width < 0 || layoutParams.width > indicatorTabWidth) {
	// layoutParams.width = indicatorTabWidth;
	// }
	// indicatorTab.setLayoutParams(layoutParams);
	// if (isSetPage) {
	// pager.setCurrentItem(page);
	// }
	// int[] pos = new int[2];
	// Log.w("@@@@@", "" + indicatorLayout.getMeasuredWidth());
	// Log.w("@@@@@", "" + indicatorLayout.getWidth());
	// indicatorLayout.getLocationInWindow(pos);
	// Log.w("@@@@@", "" + pos[0]);
	// Log.w("@@@@@", "" + indicatorTab.getMeasuredWidth());
	// Log.w("@@@@@", "" + indicatorTab.getWidth());
	// indicatorLayout.getLocationInWindow(pos);
	// Log.w("@@@@@", "" + pos[0]);
	//
	// }
	// });
	// }

	@Override
	public void onClick(View v) {
		if (v.equals(buttonBack)) {
			getPageManager().backward();
		} else if (v.equals(textTab1)) {
			page = 0;
			pager.setCurrentItem(page);
		} else if (v.equals(textTab2)) {
			page = 1;
			pager.setCurrentItem(page);
		} else if (v.equals(textTab3)) {
			page = 2;
			pager.setCurrentItem(page);
		} else if (v.equals(button)) {
			getPageManager().forward(WorkTypeFragment.class);
		}
	}

	@Override
	public void onPageScrollStateChanged(int state) {

	}

	@Override
	public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
		int moveX = position * indicatorTab.getWidth() + positionOffsetPixels / 3;
		//
		TranslateAnimation animation = new TranslateAnimation(oldMoveX, moveX, 0, 0);
		animation.setDuration(0);
		animation.setFillAfter(true);
		indicatorTab.startAnimation(animation);
		oldMoveX = moveX;
	}

	@Override
	public void onPageSelected(int position) {
		page = position;
		pager.setCurrentItem(page);
	}

	private void requestAllWorkQuery(int type) {
		httpApp.setDialogUseful(isDialogUseful);
		httpApp.setDialogAutoDismiss(false);
		httpApp.setOnHttpResultListener(this);
		if (type == 0) {
			workQuerySession1 = new WorkQuerySession(0, 0);
			httpApp.request(workQuerySession1);
		} else if (type == 1) {
			workQuerySession2 = new WorkQuerySession(1, 0);
			httpApp.request(workQuerySession2);
		} else if (type == 2) {
			workQuerySession3 = new WorkQuerySession(2, 0);
			httpApp.request(workQuerySession3);
		}
	}

	@Override
	public void onHttpResult(HttpResult httpResult) {
		if (httpResult.isSucceed()) {
			HttpSession httpSession = httpResult.getHttpSession();
			if (httpSession.equals(workQuerySession1)) {
				jsonWorkQuery1 = new JsonWorkQuery((String) workQuerySession1.getResponseData());
				if (jsonWorkQuery1.getCode() == 1) {
					requestAllWorkQuery(1);
				} else {
					httpApp.dialogDismiss();
					Toast.makeText(getContext(), jsonWorkQuery1.getMessage(), Toast.LENGTH_SHORT).show();
				}
			} else if (httpSession.equals(workQuerySession2)) {
				jsonWorkQuery2 = new JsonWorkQuery((String) workQuerySession2.getResponseData());
				if (jsonWorkQuery2.getCode() == 1) {
					requestAllWorkQuery(2);
				} else {
					httpApp.dialogDismiss();
					Toast.makeText(getContext(), jsonWorkQuery2.getMessage(), Toast.LENGTH_SHORT).show();
				}
			} else if (httpSession.equals(workQuerySession3)) {
				jsonWorkQuery3 = new JsonWorkQuery((String) workQuerySession3.getResponseData());
				if (jsonWorkQuery3.getCode() == 1) {
					if (!isDialogUseful) {
						WorkDataManager.getInstance().clear();
					}
					WorkDataManager.getInstance().add(0, jsonWorkQuery1);
					WorkDataManager.getInstance().add(1, jsonWorkQuery2);
					WorkDataManager.getInstance().add(2, jsonWorkQuery3);
					updateViewTab();
					pager.setAdapter(new MyPageAdapter());
					layout.setVisibility(View.VISIBLE);
					if (isDialogUseful) {
						// postIndication(false);
					} else {
						if (listView != null) {
							listView.onRefreshComplete();
						}
					}
				} else {
					httpApp.dialogDismiss();
					Toast.makeText(getContext(), jsonWorkQuery3.getMessage(), Toast.LENGTH_SHORT).show();
				}
			}
		} else {
			HttpSession httpSession = httpResult.getHttpSession();
			if (httpSession.equals(workQuerySession1) || httpSession.equals(workQuerySession2) || httpSession.equals(workQuerySession3)) {
				if (listView != null) {
					listView.onRefreshComplete();
				}
			}
		}
	}

	private class MyPageAdapter extends PagerAdapter {

		@Override
		public int getCount() {
			return 3;
		}

		@Override
		public Object instantiateItem(View pager, int position) {
			LayoutInflater inflater = LayoutInflater.from(getContext());
			inflater.inflate(ResUtil.getLayoutId(Resource.layout.snailbilling_work_main_fragment), null);
			View view = inflater.inflate(ResUtil.getLayoutId(Resource.layout.snailbilling_work_main_fragment), (ViewGroup) pager, false);
			if (position == 0) {
				view.setBackgroundColor(0xffff0000);
			} else if (position == 1) {
				view.setBackgroundColor(0xff00ff00);
			} else if (position == 2) {
				view.setBackgroundColor(0xff0000ff);
			}
			OnePager onePager = new OnePager();
			onePager.setType(position);
			onePager.onCreateView(view);
			((ViewPager) pager).addView(view);
			return view;
		}

		@Override
		public void destroyItem(View pager, int position, Object view) {
			((ViewPager) pager).removeView((View) view);
		}

		@Override
		public boolean isViewFromObject(View view, Object object) {
			return view.equals(object);
		}

	}

	public class OnePager implements AdapterView.OnItemClickListener, AdapterView.OnItemLongClickListener, AbsListView.OnScrollListener, OnHttpResultListener {

		private PullToRefreshListView listView;
		private SimpleAdapter adapter;
		private List<Map<String, String>> data = new ArrayList<Map<String, String>>();

		private WorkQuerySession workQuerySession;
		private WorkDeleteSession workDeleteSession;
		private JsonWorkQuery.Problem problem;

		private int type;

		public void setType(int type) {
			this.type = type;
		}

		public void onCreateView(View view) {
			listView = (PullToRefreshListView) view.findViewById(ResUtil.getViewId(Resource.id.snailbilling_work_main_list_view));
			listView.setOnItemClickListener(this);
			listView.setOnItemLongClickListener(this);
			listView.setOnScrollListener(this);
			listView.setOnRefreshListener(new PullToRefreshListView.OnRefreshListener() {

				@Override
				public void onRefresh(PullToRefreshListView listView) {
					WorkMainFragment.this.listView = listView;
					isDialogUseful = false;
					requestAllWorkQuery(0);
				}
			});
			int resource = ResUtil.getLayoutId(Resource.layout.snailbilling_work_main_item);
			String[] from = { WorkDataManager.TEXT, WorkDataManager.TEXT2 };
			int[] to = { ResUtil.getViewId(Resource.id.snailbilling_work_main_text), ResUtil.getViewId(Resource.id.snailbilling_work_main_text2) };
			refreshList();
			adapter = new MyAdapter(getContext(), data, resource, from, to);
			listView.setAdapter(adapter);
		}

		public void refreshList() {
			data.clear();
			data.addAll(WorkDataManager.getInstance().getData(type));
			while (data.size() < 10) {
				data.add(WorkDataManager.getInstance().buildMap(null));
			}
		}

		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
			try {
				JsonWorkQuery.Problem problem = WorkDataManager.getInstance().getList(type).get(position - 1);
				WorkMoreFragment.workParams = new WorkMoreFragment.WorkParams();
				WorkMoreFragment.workParams.id = problem.getId();
				WorkMoreFragment.workParams.content = problem.getContent();
				if (problem.getState().equals("6") || problem.getState().equals("7")) {
					WorkMoreFragment.workParams.isFinish = true;
				}
				getPageManager().forward(WorkMoreFragment.class);
			} catch (Exception e) {
			}
		}

		@Override
		public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
			try {
				problem = WorkDataManager.getInstance().getList(type).get(position - 1);
				AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
				builder.setMessage("是否删除这条提问？");
				builder.setPositiveButton("删除", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						requestWorkDelete(problem.getId());
					}
				});
				builder.setNegativeButton("取消", null);
				builder.show();
			} catch (Exception e) {
			}
			return false;
		}

		@Override
		public void onScrollStateChanged(AbsListView view, int scrollState) {

		}

		@Override
		public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
			if (totalItemCount > 0 && totalItemCount <= WorkDataManager.getInstance().getCount(type) && firstVisibleItem + visibleItemCount == totalItemCount) {
				requestWorkQuery();
			}
		}

		private void requestWorkQuery() {
			HttpApp httpApp = new HttpApp(getContext());
			httpApp.setDialogUseful(false);
			workQuerySession = new WorkQuerySession(type, WorkDataManager.getInstance().getList(type).size());
			httpApp.setOnHttpResultListener(this);
			httpApp.request(workQuerySession);
		}

		private void requestWorkDelete(String workformId) {
			HttpApp httpApp = new HttpApp(getContext());
			workDeleteSession = new WorkDeleteSession(workformId);
			httpApp.setOnHttpResultListener(this);
			httpApp.request(workDeleteSession);
		}

		@Override
		public void onHttpResult(HttpResult httpResult) {
			if (httpResult.isSucceed()) {
				HttpSession httpSession = httpResult.getHttpSession();
				if (httpSession.equals(workQuerySession)) {
					JsonWorkQuery jsonWorkQuery = new JsonWorkQuery((String) workQuerySession.getResponseData());
					if (jsonWorkQuery.getCode() == 1) {
						WorkDataManager.getInstance().add(type, jsonWorkQuery);
						refreshList();
						adapter.notifyDataSetChanged();
					} else {
						Toast.makeText(getContext(), jsonWorkQuery.getMessage(), Toast.LENGTH_SHORT).show();
					}
				} else if (httpSession.equals(workDeleteSession)) {
					JsonBase jsonBase = new JsonBase((String) workDeleteSession.getResponseData());
					if (jsonBase.getCode() == 1) {
						WorkDataManager.getInstance().delete(problem);
						refreshList();
						adapter.notifyDataSetChanged();
						//
						updateViewTab();
					} else {
						Toast.makeText(getContext(), jsonBase.getMessage(), Toast.LENGTH_SHORT).show();
					}
				}
			}
		}

		private class MyAdapter extends SimpleAdapter {

			public MyAdapter(Context context, List<? extends Map<String, ?>> data, int resource, String[] from, int[] to) {
				super(context, data, resource, from, to);
			}

			@Override
			public View getView(int position, View convertView, ViewGroup parent) {
				View view = super.getView(position, convertView, parent);
				if (TextUtils.isEmpty(data.get(position).get(WorkDataManager.TEXT))) {
					view.setBackgroundColor(0xfff1f1f1);
				} else {
					view.setBackgroundResource(ResUtil.getDrawableId(Resource.drawable.snailbilling_bg_view_white));
				}
				return view;
			}
		}

	}

}
